<?php
class Pageley_Gateway_Database_EntityResultSetExtractor implements Pageley_Gateway_Database_ResultSetExtractor {
    private $type;
    private $tableName;
    private $eagerReferences;
    
    public function __construct($type, $tableName) {
        $this->type = $type;
        $this->tableName = $tableName;
        $this->eagerReferences = new Pageley_Util_ArrayMap();
        foreach($this->type->getAttributes() as $propertyName => $attribute) {
            if($attribute->isReference() && $attribute->isEager()) {
                $this->eagerReferences->put($propertyName, $attribute);
            }
        }
    }
    
    public function extractResults($resultSet) {
        $results = new Pageley_Util_ArrayMap();
        $serializer = Pageley_Serializer_Format::$SQL->getSerializer();
        while($resultSet->hasNext()) {
            $resultSet->next();
            $entity = $serializer->deserialize($resultSet, $this->type);
            $entity->setId($resultSet->get($this->tableName . "_id"));
            foreach($this->eagerReferences as $propertyName => $attribute) {
                $alias = Pageley_Util_String::addUnderscores($propertyName);
                $tableName = Pageley_Util_String::addUnderscores($attribute->getType());
                $eagerReference = $serializer->deserialize($resultSet, $attribute->getType(), $alias . "_");
                $eagerReference->setId($resultSet->get($alias . "_id"));
                $entity->set($propertyName, $eagerReference);
            }
            $results->add($entity);
        }
        return $results;
    }
}